<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1024px">
			<el-form ref="goodsDialogFormRef" :model="state.GoodsForm" size="default" label-width="90px">
        <el-tabs v-model="state.activeName" >
          <el-tab-pane label="基本信息" name="base">
            <el-row :gutter="35">
              <el-input class="hide-input"></el-input>
              <el-input type="password" class="hide-input"></el-input>
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                <el-form-item label="商品名称">
                  <el-input v-model="state.GoodsForm.goodsName" placeholder="" clearable ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="商品分类">
                  <el-cascader
                      :options="state.parents"
                      :props="{ checkStrictly: true,emitPath:false, value: 'value', label: 'label' }"
                      placeholder="请选择分类"
                      clearable
                      class="w100"
                      v-model="state.GoodsForm.goodsClassifyId"
                  >
                    <template #default="{ node, data }">
                      <span>{{ data.label }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="商品类型">
                  <el-radio-group v-model="state.GoodsForm.type">
                    <el-radio :label="1">实物</el-radio>
                    <el-radio :label="2">虚拟</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="12" class="mb20">
                <el-form-item label="市场价">
                  <el-input-number min="0" v-model="state.GoodsForm.linePrice" placeholder="" clearable></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="12" class="mb20">
                <el-form-item label="售价">
                  <el-input-number min="0" v-model="state.GoodsForm.price" placeholder="" clearable></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="12" class="mb20">
                <el-form-item label="积分">
                  <el-input-number min="0" v-model="state.GoodsForm.integral" placeholder="" clearable></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="12" class="mb20">
                <el-form-item label="库存">
                  <el-input-number min="0" v-model="state.GoodsForm.sku" placeholder="" type="number" clearable></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="12" class="mb20">
                <el-form-item label="排序">
                  <el-input-number min="0" v-model="state.GoodsForm.sort" placeholder="越大越靠前" type="number" clearable></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
                <el-form-item label="状态">
                  <el-switch v-model="state.GoodsForm.status" :active-value="1" :inactive-value="0" inline-prompt active-text="上架" inactive-text="下架"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="媒体信息" name="media">
            <el-row :gutter="35">
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
                <el-form-item label="缩略图">
                  <el-upload
                      class="image-uploader"
                      :action="state.uploadImgUrl"
                      :show-file-list="true"
                      :on-success="handleUploadCover"
                      accept="image/*"
                      :headers="state.header"
                      :on-remove="clearCover"
                      :file-list="state.fileList"
                      list-type="picture-card"
                  >
                    <div style="text-align: center">
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div>300*160</div>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="35">
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
                <el-form-item label="商品相册">
                  <el-upload
                      class="image-uploader"
                      :action="state.uploadImgUrl"
                      :show-file-list="true"
                      :on-success="handleUploadImage"
                      accept="image/*"
                      :headers="state.header"
                      :on-remove="clearImage"
                      :file-list="state.imgList"
                      list-type="picture-card"
                      :multiple="true"
                      :limit="10"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="35">
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
                <el-form-item label="宣传视频">
                  <video :src="state.GoodsForm.video" controls class="video" >
                    <source :src="state.GoodsForm.video" />
                    不支持
                  </video>
                  <el-upload
                      class="video-uploader"
                      :action="state.uploadVideoUrl"
                      :show-file-list="true"
                      :on-success="handleUploadVideo"
                      :on-remove="clearVideo"
                      :file-list="state.videoList"
                      accept="video/*"
                      :headers="state.header"
                      :limit="1"
                      style="padding-left: 10px;width:50%;"
                  >
                    <el-button type="primary" size="default">上传视频</el-button>
                  </el-upload>
                  <el-input v-model="state.GoodsForm.video" placeholder="手动填写视频地址" clearable style="margin-top: 5px;"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="detail">
            <el-row :gutter="35">
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
                <el-form-item label="商品详情">
                  <Editor v-model:get-html="state.GoodsForm.detail" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="param" style="min-height: 300px;">
            <el-row :gutter="35" v-for="(v, k) in state.GoodsForm.param" :key="k">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="名称" >
                  <template #label>
                    <el-button type="primary" circle size="small" @click="onAddRow" v-if="k === 0">
                      <el-icon>
                        <ele-Plus />
                      </el-icon>
                    </el-button>
                    <el-button type="danger" circle size="small" @click="onDelRow(k)" v-else>
                      <el-icon>
                        <ele-Delete />
                      </el-icon>
                    </el-button>
                    <span class="ml10">名称</span>
                  </template>
                  <el-input v-model="state.GoodsForm.param[k].name" style="width: 100%" placeholder="请输入"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="参数值" >
                  <el-input v-model="state.GoodsForm.param[k].value" style="width: 100%" placeholder="请输入"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="排序">
                  <el-input-number min="0" v-model="state.GoodsForm.param[k].sort" style="width: 100%" placeholder="请输入"> </el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品规格" name="spec" style="min-height: 300px;">
            <el-row>
              <el-button type="success" @click.prevent="addSpec()" class="ml34">添加规格项</el-button>
            </el-row>
            <el-form-item
                v-for="(spec, index) in state.GoodsForm.spec"
                :label="'规格' + (index+1)"
                :key="index"
                style="width:100%"
                class="mb20"
            >
              <el-row :gutter="10" class="mb10">
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-input v-model="spec.name" @change="createItems"></el-input>
                </el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
                  <el-button @click.prevent="removeSpec(index)">删除规格项</el-button>
                </el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
                  <el-button type="primary" @click.prevent="addSpecValue(index)">添加规格值</el-button>
                </el-col>
              </el-row>
              <div style="height: 1px;width:100%;"></div>
              <el-row :gutter="5">
                <el-col :xs="8" :sm="6" :md="4" :lg="4" :xl="4" v-for="(vi, vii) in spec.value">
                  <el-input v-model="vi.value" @change="specValueChange(index,vii)"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-row class="mt20">
              <div>
                <h2 class="title">规格明细</h2>
                <span>批量设置：
                <span class="batch-btn" @click="batchSet('linePrice')">市场价</span>
                <span class="batch-btn" @click="batchSet('price')">销售价</span>
                <span class="batch-btn" @click="batchSet('sku')">库存</span></span>
              </div>
            </el-row>
            <el-row class="mt10">
              <el-table
                  :data="state.GoodsForm.items"
                  style="width:100%"
                  border
              >
                <el-table-column
                    v-for="(s,index) in state.GoodsForm.spec"
                    :prop="'sv'+index"
                    :label="s.name"
                    >
                </el-table-column>
                <el-table-column
                    prop="linePrice"
                    label="市场价"
                    width="170"
                    >
                  <template v-slot="scope">
                    <div class="table-input-item">
                      <el-input-number min="0" v-model="scope.row.linePrice" placeholder="输入市场价" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="linePrice"
                    label="销售价"
                    width="170">
                  <template v-slot="scope">
                    <div class="table-input-item">
                      <el-input-number min="0" v-model="scope.row.price" placeholder="输入销售价" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="linePrice"
                    label="库存"
                    width="170">
                  <template v-slot="scope">
                    <div class="table-input-item">
                      <el-input-number min="0" v-model="scope.row.sku" placeholder="输入库存" />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-tab-pane>
        </el-tabs>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import {defineAsyncComponent, reactive, ref} from 'vue';
import { useGoodsApi } from '/@/api/shop/goods';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义父组件传过来的值
const props = defineProps({
  // 列表内容
  data: {
    type: Array<any>,
    default: () => [],
  }
});

//引入富文本编辑器
const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));

// 定义变量内容
const goodsDialogFormRef = ref();
const baseUrl = import.meta.env.VITE_API_URL;

const state = reactive({
	GoodsForm: {
		id:0,//用户id
    type: 1,//类型
		goodsName: '', // 名称
    goodsClassifyId: 0,//分类id
		cover: '', // 缩略图
		images: [], // 图册
		video: '', // 视频
		price: '', // 售价
		linePrice: '', // 市场价
		integral: '', // 积分
		sku: '', // 库存
		sort: '', // 排序
		detail: '', // 详情
		param: [], // 参数
    spec: [],//规格
    items: [],//多规格
		status: 1, // 状态
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	header:{Authorization: Session.get('token')},//上传请求头
	uploadImgUrl: baseUrl+'AdminUpload/image',//图片上传地址
  uploadVideoUrl: baseUrl+'AdminUpload/video',//视频上传地址
	fileList: [],
  imgList: [],
  videoList: [],
	parents: [],
  activeName: 'base'
});
//删除规格
const removeSpec = (index: number) => {
  if (index !== -1) {
    state.GoodsForm.spec.splice(index, 1)
    createItems();
  }
}
//新增规格
const addSpec = () => {
  if(state.GoodsForm.spec.length >= 3){
    return ElMessage.error('最多只能添加3条规格');
  }
  state.GoodsForm.spec.push({
    id: 0,
    name: '',
    value: [],
  });
}
//添加规格值
const addSpecValue = (index) => {
  if(state.GoodsForm.spec[index].name === ''){
    return ElMessage.error('请先填写规格名称');
  }
  ElMessageBox.prompt('输入规格值',{
    inputType: 'textarea',
    inputPlaceholder: '每行一个',
  }).then(({value}) => {
    let arr = value.split('\n');
    arr = arr.filter(val => val !== '');
    if(arr.length){
      let specValue = [];
      arr.forEach(val => {
        specValue.push({specId:0,value:val,id:0});
      });
      state.GoodsForm.spec[index].value.push(...specValue);
    }
    createItems();
  }).catch(()=>{});
}
//改变规格值
const specValueChange = (si: number, vi: number) => {
  if(state.GoodsForm.spec[si].value[vi].value === ''){
    state.GoodsForm.spec[si].value.splice(vi, 1);
  }
  createItems();
}
// 新增参数行
const onAddRow = () => {
  state.GoodsForm.param.push({
    id: 0,
    name: '',
    value: '',
    sort: String(state.GoodsForm.param.length),
  });
};
// 删除参数行
const onDelRow = (k: number) => {
  state.GoodsForm.param.splice(k, 1);
};
//缩略图上传成功
const handleUploadCover = (
    response:any,
    uploadFile:any
) => {
  if(!response.code){
    state.GoodsForm.cover = response.data;
    state.fileList = [
      {name:uploadFile.name,url:response.data}
    ];
  }else{
    ElMessage.error(response.msg);
  }
}
//视频上传成功
const handleUploadVideo = (
    response:any,
    uploadFile:any
) => {
  if(!response.code){
    state.GoodsForm.video = response.data;
    state.videoList = [
      {name:uploadFile.name,url:response.data}
    ];
  }else{
    ElMessage.error(response.msg);
  }
}
//相册上传成功
const handleUploadImage = (
    response:any,
    uploadFile:any
) => {
  if(!response.code){
    state.GoodsForm.images.push(response.data);
    state.imgList.push({name:uploadFile.name,url:response.data});
  }else{
    ElMessage.error(response.msg);
  }
}
const getImageList = (imgs: Array<string>) => {
  let images = [];
  imgs.forEach(img => {
    images.push({
    name: img.substring(img.lastIndexOf('/')+1), url: img
    });
  })
  return images;
}
//清除值
const clearCover = () => {
    state.GoodsForm.cover = '';
    state.fileList = [];
}
//清除值
const clearVideo = () => {
  state.GoodsForm.video = '';
  state.videoList = [];
}
//清除值
const clearImage = (file: string,fileList: Array<Object>) => {
  let images = [];
  fileList.forEach(value => {
     images.push(value.url);
  });
  state.GoodsForm.images = images;
}
//获取多级数据
const getParentData = () => {
  return props.data;
};
// 打开弹窗
const openDialog = (type: string, row: any) => {
  state.fileList = [];
  state.imgList = [];
  state.videoList = [];
	if (type === 'edit') {

		var info = row;
		info = getFormData(info);
    info.goodsClassifyId = parseInt(info.goodsClassifyId);
    //处理缩略图
    if(info.cover){
      state.fileList = [
        {name: info.cover.substring(info.cover.lastIndexOf('/')+1), url: info.cover}
      ];
    }
    //处理相册
    if(info.images.length){
       state.imgList = getImageList(info.images);
    }
    //处理视频
    if(info.video){
      state.videoList = [
        {name: info.video.substring(info.video.lastIndexOf('/')+1), url: info.video}
      ];
    }

		state.GoodsForm = info;
    getDetail(info.id);
		state.dialog.title = '修改';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';

	} else {
		state.dialog.title = '新增';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = 'add';

		// 清空表单
		state.GoodsForm = {
      id:0,//用户id
      type: 1,//类型
      goodsName: '', // 名称
      goodsClassifyId: 0,//分类id
      cover: '', // 缩略图
      images: [], // 图册
      video: '', // 视频
      price: '', // 售价
      linePrice: '', // 市场价
      integral: '', // 积分
      sku: '', // 库存
      sort: '', // 排序
      detail: '', // 详情
      param: [
        {name:'',value:'',sort:'1'}
      ], // 参数
      spec: [],//规格
      items: [],//多规格
      status: 1, // 状态
		};
	}
	state.dialog.isShowDialog = true;
	state.parents = getParentData();
};
//获取详情
const getDetail = (id: number) => {
  useGoodsApi().getAdminGoodsDetail({id:id}).then(res => {
    if(!res.code){
       state.GoodsForm.detail = res.data.detail;
       state.GoodsForm.param = res.data.param;
       state.GoodsForm.spec = res.data.spec;
       state.GoodsForm.items = res.data.items;
    }
  }).catch(err=>{
    console.log(err);
  });
}
//填充提交数据
const getFormData = (data: any) => {
	var newData = {} as any,i;
	for(i in state.GoodsForm){
		newData[i] = data[i];
	}
	return newData;
}
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {

	useGoodsApi().setAdminGoods(state.GoodsForm).then(res=>{
		if(!res.code){
			ElMessage.success(state.dialog.title+'成功');
      // 清空表单
      state.GoodsForm = {
        id:0,//用户id
        type: 1,//类型
        goodsName: '', // 名称
        goodsClassifyId: 0,//分类id
        cover: '', // 缩略图
        images: [], // 图册
        video: '', // 视频
        price: '', // 售价
        linePrice: '', // 市场价
        integral: '', // 积分
        sku: '', // 库存
        sort: '', // 排序
        detail: '', // 详情
        param: [], // 参数
        spec: [],//规格
        items: [],//多规格
        status: 1, // 状态
      };
      closeDialog();
      emit('refresh');
		}
	}).catch(err=>{
		console.log(err);
	});
};
//生成items数组
const createItems = () => {
  let specs = state.GoodsForm.spec.filter(s => s.name != '' && s.value.length);
  if(!specs.length){
    return !1;
  }
  let items = [],oldItems = {};
  if(state.GoodsForm.items.length){
    state.GoodsForm.items.forEach(v=>{
      if(v.ids){
        oldItems[v.ids] = v;
      }
    })
  }
  specs[0].value.forEach( (val) => {
    if(specs.length === 1){
      //单规格
      let vs = val.value, ids = val.id?String(val.id):'';
      items.push({
        id:oldItems[ids] ? oldItems[ids].id:0,
        sv0: vs,
        logo: oldItems[ids]?oldItems[ids].logo:'',
        linePrice: oldItems[ids]?oldItems[ids].linePrice:'',
        price: oldItems[ids]?oldItems[ids].price:'',
        sku: oldItems[ids]?oldItems[ids].sku:'',
        value: vs,
        ids: ids
      });
    }else if(specs.length === 2){
      //双规格
      specs[1].value.forEach( vol => {
        let vs = val.value + ',' + vol.value;
        let ids = val.id && vol.id ? val.id + ',' + vol.id :'';
        items.push({
          id: oldItems[ids] ? oldItems[ids].id:0,
          sv0: val.value,
          sv1: vol.value,
          logo: oldItems[ids] ? oldItems[ids].logo : '',
          linePrice: oldItems[ids] ? oldItems[ids].linePrice : '',
          price: oldItems[ids] ? oldItems[ids].price : '',
          sku: oldItems[ids] ? oldItems[ids].sku : '',
          value: vs,
          ids: ids
        })
      });
    }else{
      //多规格
      specs[1].value.forEach( vol => {
        let vs = val.value+','+vol.value;
        specs[2].value.forEach( vvl => {
          let vvs = vs+','+vvl.value;
          let ids = val.id && vol.id && vvl.id? val.id + ',' + vol.id + ',' + vvl.id :'';
          items.push({
            id: oldItems[ids] ? oldItems[ids].id:0,
            sv0: val.value,
            sv1: vol.value,
            sv2: vvl.value,
            logo: oldItems[ids] ? oldItems[ids].logo : '',
            linePrice: oldItems[ids] ? oldItems[ids].linePrice : '',
            price: oldItems[ids] ? oldItems[ids].price : '',
            sku: oldItems[ids] ? oldItems[ids].sku : '',
            value: vvs,
            ids: ids
          })
        });
      });
    }
  });
  state.GoodsForm.items = items;
}
//批量设置
const batchSet = (type: string) => {
  if(!state.GoodsForm.items.length){
    return !1;
  }
  let title = type==='linePrice'?'市场价':(type==='price'?'销售价':'库存');
  ElMessageBox.prompt('请输入'+title,{
    inputType: 'text',
  }).then(({value}) => {
    state.GoodsForm.items.forEach(item => {
      item[type] = value;
    })
  }).catch(()=>{});
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style>
.hide-input{
  outline: none;
  border: none;
  overflow: hidden;
  width: 0;
  height: 0;
}
.video{
  width:50%;
  height: 180px;
  background-color: #000000;
}
.batch-btn{
  cursor: pointer;color:#409EFF;margin-right: 20px;
}
.table-input-item .el-form-item__content{
  margin-left: 0 !important;
}
</style>
